package net.onmotion.util;

import java.util.Date;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;

public class Log implements CommandListener {
  public static String logText;
  public static Form formLogConsole;
  public static StringItem itemLog;
  public static Log log = null;
  public static MIDlet midlet;
  public static Displayable current; 
  
  private Log(){
    
  }
  
  public static Log instance(){
    if (log == null){
      log = new Log();
    }
    return log;
  }
  
  /**
   * Adds the text information to the log.
   * @param text
   */
  public static void log(String text) {
    if (logText == null) {
      logText = new String();
    }
    Date date = new Date();
    logText = date.toString() + ":" + text + "\n" + logText;
    System.out.println(text);
  }

  public static void log(Throwable e) {
    log(e.toString(), e);        
  }
  
  public static void log(String text, Throwable e) {
    log(text);
    e.printStackTrace();    
  }
  /**
   * Returns the log form.
   * @return
   */
  public static Displayable showConsole(){
    if (formLogConsole == null) {
      formLogConsole = new Form("Log");
      itemLog = new StringItem("", "");
      formLogConsole.append(itemLog);
      formLogConsole.addCommand(new Command("Back", Command.BACK, 1));
      formLogConsole.addCommand(new Command("Clear", Command.ITEM, 1));
      formLogConsole.setCommandListener(instance());
    }
    current = Display.getDisplay(midlet).getCurrent();
    itemLog.setText(Log.logText);
    return formLogConsole;
  }

  /**
   * Reacts to events in the log form.
   */
  public void commandAction(Command cmd, Displayable display) {
    if (cmd.getLabel().equals("Back")){
      Display.getDisplay(midlet).setCurrent(current);
    } else if (cmd.getLabel().equals("Clear")){
      logText = "";
      itemLog.setText(Log.logText); 
    }    
  }

}
